package net.wangds.imagecomp.comp;

import net.wangds.common.base.space.Loc;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;

@Component
public class ImageClipComp {

    public static final Color COLOR_TRANSLUCENT = new Color(0xFF,0xFF,0xFF, 0x0);

    /**
     * 裁剪椭圆区域.
     * @param img 原图.
     * @param loc 起始位置.
     * @param radiusX 椭圆宽度.
     * @param radiusY 椭圆高度.
     * @param bgColor 背景色.
     *                <p>默认透明.</p>
     */
    public static BufferedImage clipEllipse(BufferedImage img, Loc<Double> loc,double radiusX, double radiusY, Color bgColor){
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage bi = BufferedImageComp.toTranslucentImage(img);

        DrawOperate.draw(bi.getGraphics(), (g)->{

            g.setBackground(bgColor==null?COLOR_TRANSLUCENT:bgColor);
            g.clearRect(0,0,w,h);

            if(loc!=null) {
                g.setClip(new Ellipse2D.Double(loc.getLeft(), loc.getTop(), radiusX, radiusY));
                g.drawImage(img, 0,0,null);

            }

        });

        return bi;

    }

    /**
     * 图片中心剪切最大的圆.
     * <p>四周被剪切掉的部分为透明.</p>
    * @param img 图片.
     */
    public static BufferedImage clipCircle(BufferedImage img){
        int width = img.getWidth();
        int height = img.getHeight();
        int size = Math.max(Math.min(width, height),1);
        int top = (height-size)/2;
        int left = (width-size)/2;
        return clipEllipse(img,Loc.of((double)top, (double)left), size, size, null);
    }

}
